package com.hluobo.library.service.impl;

import java.sql.Date;
import java.util.List;

import javax.persistence.Query;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import com.hluobo.library.dao.impl.BasicDao;
import com.hluobo.library.model.User;
import com.hluobo.library.service.UserService;

@Component("userService")
public class UserServiceImpl extends BasicDao implements UserService{

	@Override
	public User login(String username, String password){
		
		String sql = "From User u where u.username=? and u.password = ?";
		Query  query = em.createQuery(sql)
				.setParameter(1, username).setParameter(2, password);
		List<User> users = query.getResultList();
		//System.out.println(users.size());
		return users.size()>0?users.get(0):null;
		
	}

	@Override
	public boolean saveUserInfo(JSONObject infoObject) {
		boolean flag = false;
		try {
			int id = infoObject.getInt("id");
			User u = this.query(User.class, id);
			u.setName(infoObject.has("name") ? infoObject.getString("name") : null);
			u.setSex(infoObject.has("sex") ? infoObject.getBoolean("sex") : false);
			u.setEmail(infoObject.has("email") ? infoObject.getString("email") : null);
			u.setBirthday(infoObject.has("birthday") ? Date.valueOf(infoObject.getString("birthday")) : null);
			u.setAcadmy(infoObject.has("acadmy") ? infoObject.getString("acadmy") : null);
			u.setMajor(infoObject.has("major") ? infoObject.getString("major") : null);
			u.setDormitory(infoObject.has("dormitory") ? infoObject.getString("dormitory") : null);
			u.setNote(infoObject.has("note") ? infoObject.getString("note") : null);
			this.update(u);
			flag = true;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
		return flag;
	}
	
}
